import { useState, useRef, useEffect } from 'react';
export default function Timer() {
    const [time, setTime] = useState(0);
    const intervalRef = useRef(null);
    const isRunningRef = useRef(false);

    const startTimer = () => {
        if (!isRunningRef.current) {
            isRunningRef.current = true;
            intervalRef.current = setInterval(() => {
                setTime(prevTime => prevTime + 1);
            }, 1000);
        }
    };

    const stopTimer = () => {
        if (isRunningRef.current) {
            isRunningRef.current = false;
            clearInterval(intervalRef.current);
        }
    };

    const resetTimer = () => {
        stopTimer();
        setTime(0);
    };

    useEffect(() => {
        // 清理定时器
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, []);

    return (
        <div>
            <h2>计时器: {time}秒</h2>
            <button onClick={startTimer}>开始</button>
            <button onClick={stopTimer}>停止</button>
            <button onClick={resetTimer}>重置</button>
        </div>
    );
}